package com.bookstore.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.back.entity.NewsCategoryRelation;
import com.bookstore.back.mapper.NewsCategoryRelationMapper;
import com.bookstore.back.service.NewsCategoryRelationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 新闻分类关系服务实现类
 * 
 * @author 程序猿_Ti
 * @since 2025-07-23
 */
@Service
public class NewsCategoryRelationServiceImpl extends ServiceImpl<NewsCategoryRelationMapper, NewsCategoryRelation> 
        implements NewsCategoryRelationService {

    @Override
    @Transactional
    public boolean updateNewsCategories(Integer newsId, List<Integer> categoryIds) {
        // 删除原有的分类关系
        QueryWrapper<NewsCategoryRelation> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.eq("news_id", newsId);
        this.remove(deleteWrapper);

        // 添加新的分类关系（只取第一个分类，确保一对一关系）
        if (categoryIds != null && !categoryIds.isEmpty()) {
            NewsCategoryRelation relation = new NewsCategoryRelation();
            relation.setNewsId(newsId);
            relation.setCategoryId(categoryIds.get(0)); // 只取第一个分类

            return this.save(relation);
        }

        return true;
    }

    @Override
    public List<Integer> getCategoryIdsByNewsId(Integer newsId) {
        QueryWrapper<NewsCategoryRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("news_id", newsId);
        
        return this.list(queryWrapper).stream()
                .map(NewsCategoryRelation::getCategoryId)
                .collect(Collectors.toList());
    }

    @Override
    public List<Integer> getNewsIdsByCategoryId(Integer categoryId) {
        QueryWrapper<NewsCategoryRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId);
        
        return this.list(queryWrapper).stream()
                .map(NewsCategoryRelation::getNewsId)
                .collect(Collectors.toList());
    }
}
